<template>
  <div>
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog"
      :custom-class="'panna-dialog_big'"
      :append-to-body="true"
      :title="dataList.UsageLogInfo"
      align="center"
      destroy-on-close
      :visible.sync="innerDialogFormVisible"
      @closed="closeDialog"
    >
      <div>
        <el-divider class="el-divider-specail" content-position="left"
          ><span style="color: red">*</span>
          <span>{{ dataList.UsageDevice }}</span>
          <el-button
            type="primary"
            style="margin-left: 20px"
            @click="choiceDevice"
            >{{ dataList.SelectDevice }}</el-button
          >
        </el-divider>
        <el-table
          :data="list"
          element-loading-text="Loading"
          fit
          height="330px"
          highlight-current-row
        >
          <el-table-column :label="dataList.DeviceNumber">
            <template slot-scope="scope">
              {{ scope.row.num }}
            </template>
          </el-table-column>
          <el-table-column
            :label="
              $i18n.locale === 'en' ? dataList.DeviceEName : dataList.DeviceName
            "
          >
            <template slot-scope="scope">
              {{ scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column :label="dataList.DeviceSpecifications">
            <template slot-scope="scope">
              {{ scope.row.specifications }}
            </template>
          </el-table-column>

          <el-table-column :label="dataList.DeviceClassifyId">
            <template slot-scope="scope">
              {{ scope.row.classifyName }}
            </template>
          </el-table-column>

          <el-table-column :label="dataList.DeviceSupplierName">
            <template slot-scope="scope">
              {{ scope.row.supplierName }}
            </template>
          </el-table-column>
          <el-table-column :label="dataList.DeviceFactoryNum">
            <template slot-scope="scope">
              {{ scope.row.factoryNum }}
            </template>
          </el-table-column>

          <el-table-column :label="dataList.DeviceStatus">
            <template slot-scope="scope">
              {{ scope.row.statusName }}
            </template>
          </el-table-column>
          <el-table-column :label="dataList.DeviceUseState">
            <template slot-scope="scope">
              <span>
                {{ scope.row.useStateLabel }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            :label="
              $i18n.locale === 'en'
                ? dataList.eDeviceStorageAddress
                : dataList.DeviceStorageAddress
            "
          >
            <template slot-scope="scope">
              {{ scope.row.storageAddress }}
            </template>
          </el-table-column>
          <el-table-column :label="dataList.DevicePersonResponsibleId">
            <template slot-scope="scope">
              {{ scope.row.personResponsibleName }}
            </template>
          </el-table-column>
          <el-table-column :label="dataList.Operation">
            <template slot-scope="scope">
              <div class="base-table-operation">
                <el-link
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index)"
                  >{{ btn.Delete }}</el-link
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-divider class="el-divider-specail" content-position="left">
        <span>{{ dataList.UsageInfo }}</span>
      </el-divider>
      <div>
        <el-form
          ref="formData"
          :label-width="formLabelWidth"
          :model="formData"
          :rules="formDataRules"
          status-icon
        >
          <el-row>
            <el-col :span="12">
              <el-form-item
                :label="dataList.UsageName"
                prop="userIdList"
                :error="errorMsg.userIdList"
              >
                <UserDropDownList
                  :value="formData.userIdList"
                  :multiple="multiple"
                  :borrow-person-change="borrowPersonChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :label="dataList.BeginUsageTime"
                prop="startTime"
                :error="errorMsg.startTime"
              >
                <el-date-picker
                  v-model="formData.startTime"
                  type="datetime"
                  :placeholder="dataList.SelectDateTime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item
                :label="dataList.ReasonsOfUsage"
                prop="reasonsForUsing"
                :error="errorMsg.reasonsForUsing"
              >
                <el-input
                  v-model="formData.reasonsForUsing"
                  type="textarea"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="onSubmit('formData')">{{
          btn.Save
        }}</el-button>
        <el-button @click="cancel">{{ btn.Cancel }}</el-button>
      </div>
      <DeviceDialogList
        v-if="choiceDeviceVisible"
        :dialog-form-visible.sync="choiceDeviceVisible"
        :device-id-list="deviceIdList"
        :checked-rows="checkedRows"
        :query-form-parent="queryFormParent"
        @checkedRowsFun="closeChoiceDevice"
      />
    </el-dialog>
  </div>
</template>

<script>
import { create } from "../../api/DeviceUsageLog.js";
import DeviceDialogList from "../../components/DeviceDialogList.vue";
import UserDropDownList from "../../components/UserDropDownList.vue";
import { formatTime } from "../../utils/time";

export default {
  name: "DeviceUsageLogAdd",
  components: {
    DeviceDialogList,
    UserDropDownList,
  },
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      formatTime,
      loading: false,
      multiple: true,
      innerDialogFormVisible: false,
      choiceDeviceVisible: false,
      formLabelWidth: "130px",
      list: [],
      checkedRows: [],
      deviceIdList: [],
      queryFormParent: {
        urlConditionString: "",
        device: "",
        personResponsibleName: "",
        num: "",
        name: "",
        specifications: "",
        classifyId: "-1",
        statusId: "-1",
        storageAddress: "",
        factoryNum: "",
        personResponsibleId: 0,
        updateDateArray: [],
        startTime: null,
        endTime: null,
        departId: "0",
        usageState: 0,
      },
      formData: {
        id: 0,
        userId: "",
        userIdList: "",
        startTime: null,
        reasonsForUsing: "",
        deviceId: [],
      },
      formDataRules: {
        userIdList: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        startTime: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        reasonsForUsing: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
      },
      initErrorMsg: {
        userId: "",
        startTime: "",
        reasonsForUsing: "",
        deviceId: "",
      },
      errorMsg: {
        userId: "",
        startTime: "",
        reasonsForUsing: "",
        deviceId: "",
      },
    };
  },
  computed: {
    btn() {
      return this.$t("ModuleDevice.buttons");
    },
    dataList() {
      return this.$t("ModuleDevice.Device");
    },
  },
  watch: {
    innerDialogFormVisible(val) {
      this.$emit("update:dialogFormVisible", val);
    },
  },
  created() {
    this.formData.startTime = formatTime(new Date(), "YYYY-MM-DD HH:mm:ss");
    this.innerDialogFormVisible = this.dialogFormVisible;
  },
  methods: {
    borrowPersonChange(val) {
      this.formData.userId = 0;
      this.formData.userIdList = val;
    },
    // 关闭选择设备弹框
    closeChoiceDevice(data) {
      this.list = data;
    },
    // 选择设备
    choiceDevice() {
      this.checkedRows = this.list;
      this.choiceDeviceVisible = true;
    },
    cancel() {
      this.innerDialogFormVisible = false;
      this.$emit("update:dialogFormVisible", false);
      this.$emit("close");
    },
    closeDialog() {
      this.cancel();
    },
    handleDelete(index) {
      this.list.splice(index, 1);
    },
    onSubmit() {
      if (
        this.list === undefined ||
        this.list === null ||
        this.list.length === 0
      ) {
        this.$message.warning(this.$t("ModuleDevice.Message.SelectEquipToUse"));
        return false;
      }
      this.formData.deviceId = this.list.map((x) => x.id);
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
          create(this.formData)
            .then((res) => {
              if (res.code === 200) {
                this.closeDialog();
              } else {
                this.showValidateMsgCheck(res);
              }
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("deviceId", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("userIdList", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("reasonsForUsing", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("startTime", this.errorMsg, res.msg);
      }
    },
  },
};
</script>
